package com.xu.cloud.common.tx;

import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import java.util.Objects;

/**
 * PlatformTransactionManager事务管理
 *
 * @author xuguan
 * @since 2024/11/8
 * @see org.springframework.transaction.PlatformTransactionManager
 */
public class PlatformITransaction implements ITransaction {

    private final PlatformTransactionManager ptm;
    private TransactionStatus ts = null;

    public PlatformITransaction(PlatformTransactionManager ptm) {
        this.ptm = ptm;
    }

    @Override
    public void startTransaction() {
        ts = ptm.getTransaction(getTransactionDefinition());
    }

    @Override
    public void commit() {
        if (Objects.isNull(ts)) {
            throw new UnsupportedOperationException("transaction not start");
        }
        ptm.commit(ts);
    }

    @Override
    public void rollback() {
        if (Objects.isNull(ts)) {
            throw new UnsupportedOperationException("transaction not start");
        }
        ptm.rollback(ts);
    }

    public TransactionDefinition getTransactionDefinition() {
        final DefaultTransactionDefinition td = new DefaultTransactionDefinition();
        td.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED);
        td.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
        return td;
    }
}
